﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentNHibernate.Cfg;
using NHibernate;
using FluentNHibernate.Cfg.Db;
using System.Reflection;

namespace Zeus.DAL.NHibernate
{
    public enum DbType
    {
        MSSQL2008 = 1,
        ORACLE = 2,
        MYSQL = 3,
        MSSQL2012 = 4
    }
    
    public class NHibernateDb<TMap>
    {
        private readonly string _connectionString;
        private DbType dbType;
        private ISessionFactory _sessionFactory;

        public ISessionFactory SessionFactory
        {
            get { return _sessionFactory ?? (_sessionFactory = CreateSessionFactory()); }
        }

        public NHibernateDb(string connectionString, DbType dbType)
        {
            this.dbType = dbType;
            _connectionString = connectionString;
        }

        private ISessionFactory CreateSessionFactory()
        {
            switch (dbType)
            {
                case DbType.MSSQL2008:
                    return Fluently.Configure()
                        .Database(MsSqlConfiguration.MsSql2008.ConnectionString(_connectionString))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TMap>())
                        .BuildSessionFactory();
                case DbType.MSSQL2012:
                    return Fluently.Configure()
                        .Database(MsSqlConfiguration.MsSql2012.ConnectionString(_connectionString))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TMap>())
                        .BuildSessionFactory();
                case DbType.ORACLE:
                    return Fluently.Configure()
                        .Database(OracleConfiguration.Oracle10.ConnectionString(_connectionString))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TMap>())
                        .BuildSessionFactory();
                case DbType.MYSQL:
                    return Fluently.Configure()
                        .Database(MySQLConfiguration.Standard.ConnectionString(_connectionString))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TMap>())
                        .BuildSessionFactory();
                default:
                    return Fluently.Configure()
                        .Database(MsSqlConfiguration.MsSql2008.ConnectionString(_connectionString))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TMap>())
                        .BuildSessionFactory();
            }
            
        }
    }

}
